package dssd.gui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContextEvent;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import dssd.modelo.SolicitudAlta;
import dssd.servicios.AbstractService;
import dssd.servicios.ConductorService;
import dssd.servicios.IAbstractService;
import dssd.servicios.IConductorService;
import dssd.servicios.ILicenciasService;
import dssd.servicios.ILoginService;
import dssd.servicios.IUsuarioService;
import dssd.servicios.UsuarioService;

public final class ServiceLocator {

    private static IAbstractService getService(String serviceName){
    	loadProperties();
    	String[] paths = {"webApplicationContext.xml"};
    	ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
    	return (IAbstractService) ctx.getBean(serviceName);
    }
    
    private static void loadProperties() {
		// TODO Auto-generated method stub
    	final String DSSD_PROPERTIES_LOCATION = "DSSD_PROPERTIES_LOCATION_DESKTOP";

		String location = System.getenv(DSSD_PROPERTIES_LOCATION);
		if (location != null) {
			Properties properties = new Properties();
			try {
				properties.load(new FileInputStream(new File(location)));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for (Object key : properties.keySet()) {
				System.setProperty(key.toString(), properties.getProperty(key.toString().trim()));
			}
		}
		
	}

	private static ILoginService loginService = null;
    private static ILicenciasService licenciasService = null;
    private static IConductorService conductorService = null;
    private static IUsuarioService usuarioService = null;
	
    
    public static ILicenciasService getLicenciasService(){
    	if (licenciasService == null)
    		licenciasService =(ILicenciasService) getService("licenciasService");
    	return licenciasService;
    }


	public static IConductorService getConductorService() {
		if (conductorService == null)
			conductorService = (IConductorService) getService("conductorService");
		return conductorService;
	}
	
	public static IUsuarioService getUsuarioService() {
		if (usuarioService == null)
			usuarioService = (IUsuarioService) getService("usuarioService");
		return usuarioService;
	}
	
	public static ILoginService getLoginService(){
		if (loginService == null){
			loginService = (ILoginService) getService("loginService");
		}
		return loginService;
	}
}
